﻿using System;
using System.Data;
using System.Reflection;
using DevExpress.XtraEditors;
using System.Windows.Forms;

namespace QL_Truong_Hoc.DanhMuc
{
    public partial class frmDonVi : DevExpress.XtraEditors.XtraForm
    {
        private const string mcstrRoleCode = "danh_muc_dung_chung";
        private clsEnum.FORM_MODE memMode;

        private int mintDvID;
        //private string mstrDvMa;
        private DevExpress.XtraTreeList.Nodes.TreeListNode mobjCurrentNode;

        public frmDonVi()
        {
            InitializeComponent();
        }

        private void frmKhoa_Load(object sender, EventArgs e)
        {
            if (!clsCommon.fncCheckRole(Program.glstRoles, mcstrRoleCode))
            {
                this.BeginInvoke(new MethodInvoker(this.Close));
                return;
            }
            // TODO: This line of code loads data into the 'qLTHDataSet.mDonViQuanDoi' table. You can move, or remove it, as needed.
            this.mDonViQuanDoiTableAdapter.Fill(this.qLTHDataSet.mDonViQuanDoi);

            treeDonVi.ExpandAll();
            comboTreeLookup.ExpandAll();

            xInit();
        }

        private bool xInit()
        {
            bool blnResult = false;
            try
            {
                this.memMode = clsEnum.FORM_MODE.ADD;
                xClear();
                xLockControl(true);

                return true;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }

            return blnResult;
        }

        private bool xLockControl(bool blnStatus)
        {
            bool blnResult = false;
            try
            {
                mniAdd.Enabled = blnStatus;
                mniEdit.Enabled = blnStatus;
                mniDelete.Enabled = blnStatus;
                mniCancel.Enabled = !blnStatus;
                mniSave.Enabled = !blnStatus;

                txtDiaChiDonVi.Enabled = !blnStatus;
                txtTenDonVi.Enabled = !blnStatus;
                txtThuTu.Enabled = !blnStatus;
                cbDonViCha.Enabled = !blnStatus;

                treeDonVi.Enabled = blnStatus;

                return true;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }

            return blnResult;
        }

        private bool xClear()
        {
            bool blnResult = false;
            try
            {
                txtDiaChiDonVi.Text = "";
                txtTenDonVi.Text = "";
                txtThuTu.Text = "";
                cbDonViCha.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
                cbDonViCha.EditValue = null;

                return true;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }

            return blnResult;
        }

        private bool xAdd()
        {
            bool blnResult = false;
            try
            {
                DTO.MDonViQuanDoiDTO objDv;
                objDv = new DTO.MDonViQuanDoiDTO();

                int intDvID;
                intDvID = DAO.MDonViQuanDoiDAO.SelectNextIndex(Program.gobjDb);

                if(! xGetData(ref objDv, intDvID))return false;

                try
                {
                    DAO.MDonViQuanDoiDAO.Insert(Program.gobjDb, Program.gobjTrans, objDv);
                }
                catch
                {
                    clsCommon.fncMsgError("Thêm mới không thành công. Xin hãy thử lại.");
                    return false;
                }

                return true;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }

            return blnResult;
        }

        private bool xUpdate()
        {
            bool blnResult = false;
            try
            {
                DTO.MDonViQuanDoiDTO objDv;
                objDv = new DTO.MDonViQuanDoiDTO();

                int intDvID;
                intDvID = mintDvID;

                if(! xGetData(ref objDv, intDvID))return false;

                try
                {
                    DAO.MDonViQuanDoiDAO.Update(Program.gobjDb, Program.gobjTrans, objDv);
                }
                catch
                {
                    clsCommon.fncMsgError("Thêm mới không thành công. Xin hãy thử lại.");
                    return false;
                }

                return true;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }

            return blnResult;
        }

        private bool xGetData(ref DTO.MDonViQuanDoiDTO objDv, int intDvID)
        {
            bool blnResult = false;
            try
            {
                string strMaDvCha;
                object objTempNode;
                DataRowView objNode;

                strMaDvCha = "";
                objDv = new DTO.MDonViQuanDoiDTO();

                objDv.DV_ID = intDvID;
                objDv.Dv_diachi = txtDiaChiDonVi.Text.Trim();
                objDv.Dv_ten = txtTenDonVi.Text.Trim();
                objDv.Dv_thutu = (int)txtThuTu.Value;
                objDv.Dv_cha = 0;
                if (cbDonViCha.EditValue != null) objDv.Dv_cha = clsCommon.fncCnvNullToInt(cbDonViCha.EditValue);

                //lấy mã đơn vị cha
                objTempNode = cbDonViCha.Properties.GetRowByKeyValue(cbDonViCha.EditValue);
                if (objTempNode != null)
                {
                    objNode = (DataRowView)objTempNode;
                    strMaDvCha = clsCommon.fncCnvNullToString(objNode[colCombo_MaDvCha.FieldName]);
                }

                //tạo mã dv mới
                if (string.IsNullOrEmpty(strMaDvCha))
                {
                    objDv.Dv_ma = intDvID.ToString();
                }
                else
                {
                    objDv.Dv_ma = string.Format("{0}.{1}", strMaDvCha, intDvID);
                }
                return true;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }

            return blnResult;
        }

      

        private void mniSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!validRequire.Validate()) return;

                bool blnSuccess = false;

                if (this.memMode == clsEnum.FORM_MODE.ADD)
                {
                    if (clsCommon.fncDataExist(this.qLTHDataSet.mDonViQuanDoi, "dv_ten", txtTenDonVi.Text.Trim()))
                    {
                        if (!clsCommon.fncMsgConfirm("Tên đơn vị đã tồn tại. Bạn có chắc muốn tiếp tục?")) return;
                    }

                    if (!clsCommon.fncMsgConfirm("Đơn vị mới sẽ được thêm. Bạn có chắc chắn?")) return;
                    blnSuccess = xAdd();
                }
                else
                {
                    if (!clsCommon.fncMsgConfirm("Thông tin đơn vị sẽ được lưu. Bạn có chắc chắn?")) return;
                    blnSuccess = xUpdate();
                }

                if (blnSuccess)
                {
                    this.mDonViQuanDoiTableAdapter.Fill(this.qLTHDataSet.mDonViQuanDoi);

                    treeDonVi.ExpandAll();
                    comboTreeLookup.ExpandAll();

                    xLockControl(true);

                    //raise event update master table
                    Program.gevnApplication.RaiseMasterUpdate();
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void mniAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                this.memMode = clsEnum.FORM_MODE.ADD;
                xLockControl(false);
                xClear();
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void mniEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (mintDvID <= 0) return;

                this.memMode = clsEnum.FORM_MODE.EDIT;
                xLockControl(false);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void mniDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (mintDvID <= 0) return;

                if (mobjCurrentNode == null) return;

                if (mobjCurrentNode.HasChildren)
                {
                    clsCommon.fncMsgWarning("Hãy xóa đơn vị cấp dưới trước.");
                    return;
                }

                if (clsCommon.fncMsgConfirm("Bạn có chắc muốn xóa thông tin đơn vị đang được chọn?"))
                {
                    treeDonVi.DeleteNode(mobjCurrentNode);
                    mDonViQuanDoiTableAdapter.Update(qLTHDataSet.mDonViQuanDoi);
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void treeDonVi_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            try
            {
                //if (mintDvID <= 0) return;
                if (e.Node == null) return;

                this.memMode = clsEnum.FORM_MODE.EDIT;
                mobjCurrentNode = e.Node;
                xFillControl();
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private bool xFillControl()
        {
            bool blnResult = false;
            try
            {
                if (mobjCurrentNode == null) return false;

                string strTenDv;
                string strDiaChi;
                string strMaDv;
                int intDvID;
                int intDvCha;
                int intThuTu;

                strTenDv = clsCommon.fncCnvNullToString(mobjCurrentNode.GetValue(coldv_ten));
                strDiaChi = clsCommon.fncCnvNullToString(mobjCurrentNode.GetValue(coldv_diachi));
                strMaDv = clsCommon.fncCnvNullToString(mobjCurrentNode.GetValue(coldv_ma));
                intDvID = clsCommon.fncCnvNullToInt(mobjCurrentNode.GetValue(colDvID));
                intDvCha = clsCommon.fncCnvNullToInt(mobjCurrentNode.GetValue(colDvCha));
                intThuTu = clsCommon.fncCnvNullToInt(mobjCurrentNode.GetValue(coldv_thutu));

                txtDiaChiDonVi.Text = strDiaChi;
                txtTenDonVi.Text = strTenDv;
                //mstrDvMa = strMaDv;
                cbDonViCha.EditValue = intDvCha;
                mintDvID = intDvID;
                txtThuTu.Value = intThuTu;
                return true;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }

            return blnResult;
        }

        private void mniCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                this.memMode = clsEnum.FORM_MODE.EDIT;
                xClear();
                xLockControl(true);
                xFillControl();
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void treeDonVi_GetSelectImage(object sender, DevExpress.XtraTreeList.GetSelectImageEventArgs e)
        {
            if (!e.FocusedNode)
                e.NodeImageIndex = 0;
            else
                e.NodeImageIndex = 1;
        }

    }
}